#!/bin/bash
# Copyright (c) 2010, Sean A.O. Harney <sharney3@gmail.com>
#
# omf-outputlog-print-random.sh
#
# Usage:	omf-outputlog-print-random.sh [ <OMFoutputlog dir> ]
#
# Examples:	./omf-outputlog-print-random.sh OMFoutputlog.19703.__dl2_omf.yAGepx/
#		./omf-outputlog-print-random.sh		# uses ./OMFoutputlog-latest
#		./omf-outputlog-print-random.sh OMFoutputlog-latest
#

function print_usage
{
	echo -e "Usage:\t$0 [ <OMFoutputlog dir> ]" ;
}


if [ $# -gt 1 ] ; then
	print_usage ;
	exit 1 ;
fi

if [ $# -eq 1 ] ; then
	OUTPUTLOG_DIR="$1" ;
else
	OUTPUTLOG_DIR="./OMFoutputlog-latest" ;
fi

SUBDIRS_FILE="${OUTPUTLOG_DIR}/subdirs.txt" ;

if [ ! -r "${OUTPUTLOG_DIR}" ] ; then
	echo "Cannot proceed, ${OUTPUTLOG_DIR} either does not exist or is not readable." ;
	print_usage ;
	exit 1 ;
fi

# NOTE: works fine with a symlink to directory
if [ ! -d "${OUTPUTLOG_DIR}" ] ; then
	echo "Cannot proceed, ${OUTPUTLOG_DIR} is not a directory." ;
	exit 1 ;
fi

SUBDIRS_FILE_LINECOUNT=`wc -l "${SUBDIRS_FILE}" | awk '{ print $1 }'` ;
LOWER_BOUND=1 ;
UPPER_BOUND="${SUBDIRS_FILE_LINECOUNT}" ;

echo "${SUBDIRS_FILE_LINECOUNT} entries in ${SUBDIRS_FILE}" ;
echo -n "Choosing a random entry in range (${LOWER_BOUND},${UPPER_BOUND}): ... " ;

RANDOM_INTEGER=`expr "${RANDOM}" % "${UPPER_BOUND}" + ${LOWER_BOUND}` ; #awk starts linenumbers with 1
echo "${RANDOM_INTEGER}";

# NOTE: print;exit more efficient on larger files to print;exit supposedly
AWK_SCRIPT="NR == ${RANDOM_INTEGER} { print \$2; exit }" ;
SUBDIR=`awk "${AWK_SCRIPT}" "${SUBDIRS_FILE}"` ;
HASHM="##########@##########" ;
#TODO: fix this
echo;
echo ${HASHM/@/\ $SUBDIR\ } ;
echo;

for FILE in "${SUBDIR}"/*
do
	BASE_NAME=`basename "${FILE}"`
	echo ${HASHM/@/\ $BASE_NAME\ } ;
	cat "${FILE}" ;
	echo;
done

exit 0 ;
